package com.neusoft.student.controller;

import com.google.code.kaptcha.Producer;
import com.neusoft.util.Emil;
import com.neusoft.util.EmilUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/student")
@Api("学生用户")
public class StudentController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private EmilUtil emilUtil;

    @Autowired
    private RedisCache redisCache;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    // 重置密码
    @ApiOperation("重置密码")
    @PutMapping("/updatePwd")
    public  AjaxResult resetPwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();

        if (!StringUtils.isNotEmpty(loginUser.getUser().getEmail())) {
            return error("账号未绑定邮箱，无法修改密码");
        }

        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        if (sysUserService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    @ApiOperation("忘记密码")
    @GetMapping("/forgetPwd")
    public AjaxResult forgetPwd(String userName) {

        SysUser user = sysUserService.selectUserByUserName(userName);

        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        if (user.getEmail() == null) {
            return AjaxResult.error("用户未绑定邮箱");
        }

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + userName;

        String code = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            code = capText.substring(capText.lastIndexOf("@") + 1);
        }
        else if ("char".equals(captchaType))
        {
            code = captchaProducer.createText();
        }
        // 将数据储存到缓存中
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 发送邮件
        Emil emil = new Emil(user.getEmail(), "重置密码", "验证码：\n\n\n" + code, user.getUserName() + "");
        try {
            emilUtil.sendEmil(emil);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

        return AjaxResult.success("验证码已发送");
    }

    @ApiOperation("忘记密码——验证码校验")
    @GetMapping("/forgetPwdVerify")
    public AjaxResult forgetPwdVerify (String userName, String key) {
        sysUserService.forgetPwdVerify(userName, key);
        return AjaxResult.success("密码重置成功");
    }

    @GetMapping("/secUpdate")
    public AjaxResult secUpdate (String userName, String emil) {
        SysUser user = sysUserService.selectUserByUserName(userName);

        if (user == null) {
            return AjaxResult.error("用户不存在");
        }

        if (user.getEmail() == null) {
            return AjaxResult.error("用户未绑定邮箱");
        }

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + userName;

        String code = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            code = capText.substring(capText.lastIndexOf("@") + 1);
        }
        else if ("char".equals(captchaType))
        {
            code = captchaProducer.createText();
        }
        // 将数据储存到缓存中
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 发送邮件
        Emil mil = new Emil(emil, "修改安全信息", "验证码\n\n\n: " + code, user.getUserName() + "");
        try {
            emilUtil.sendEmil(mil);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

        return AjaxResult.success("验证码已发送");
    }

    @ApiOperation("修改邮箱——手机校验")
    @GetMapping("/secVerify")
    public AjaxResult secVerify (String userName, String key, String emil, String phoneNumber) {
        sysUserService.secVerify(userName, key, emil, phoneNumber);
        return AjaxResult.success("安全信息更改成功");
    }

}
